#include"Search.h"

void Search::simpleSearch(string Date)
{
		searchList.clear();//clear the search result last time

		streampos address;
		ifstream infile ("Data.txt");//note that end of file Data.txt should not include \n
		infile.seekg(-1,ios::end);
		streampos endpos = infile.tellg();
		infile.seekg(ios::beg);

		while(infile.tellg()!=endpos)
		{
     		ItemSpec* temp= new ItemSpec;
			address = infile.tellg();
			temp -> record_from_file(infile, address);
			if(Date==temp -> getDate())
				searchList.push_back(address);
			delete temp;
		}

}

streampos Search::internalSearch(ItemSpec* thisItem)
{
	
		ifstream infile ("Data.txt");
		streampos address;
		infile.seekg(-1,ios::end);
		streampos endpos = infile.tellg();
		infile.seekg(ios::beg);
		
     	//int i=0;
		while(infile.tellg()!=endpos)
		{
			//cout<<"the current address is now "<<address<<endl;
			//cout<<i<<endl;
 	        //i++;
     		ItemSpec* temp= new ItemSpec;
			address = infile.tellg();
			temp -> record_from_file(infile, address);
			if(temp->compare(*thisItem))
				{
		//			temp->print();
		//			cout<<"The positioin found is "<<infile.tellg();
					return address;
			}
			/*if(i==30) 
			{
				cout<<"reach controller i "<<endl;
			break;*/
			delete temp;
		}
		return -1;//if not found, return -1
}
bool Search::powerSearch()
{
	return true;
}
void Search::print()
{
		if(searchList.empty())
	{
		cout<<"Not found"<<endl;
	   return;
	}
	ifstream infile ("Data.txt",ios::in|ios::ate);
	streampos endpos = infile.tellg();
	infile.seekg(ios::beg);

	ItemSpec* temp=new ItemSpec;
	for(int i=0;i<searchList.size();i++)
	{	
		temp -> record_from_file(infile, searchList[i]);
		temp -> print();
	}
}

streampos Search::getAddress(int pos)
{
	return searchList[pos];
}

//add the method record_from_file to XpensItem also while in this method, have to include the read in of Status as well
XpensItem Search::getItem(int pos)
{
	ifstream infile("Data.txt");
	XpensItem* temp= new XpensItem;
	temp -> record_from_file(infile, getAddress(pos));
	return *temp;
}
